package org.eenie.kdassistant.net.xz_api;

import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;

import org.eenie.kdassistant.net.AssistantApi;
import org.eenie.kdassistant.net.ParamsAnalog;
import org.eenie.kdassistant.net.common.CommonApi;
import org.eenie.kdassistant.net.xz_api.request.DispatchReq;
import org.eenie.kdassistant.net.xz_api.request.LoginReq;
import org.eenie.kdassistant.utils.xz_encode.PwdEncode;
import org.eenie.kdassistant.utils.xz_encode.xz_http.FormBodyBuilderFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.functions.Func1;

/**
 * Created by Eenie on 2017/8/11.
 * Email: eeniework@gmail.com
 * Des:
 */

public class XingZheApi implements CommonApi {
    private XingZheService mXingZheService;
    private final int DEFUALT_TIME = 10;


    private ParamsAnalog mParamsAnalog;

    private AssistantApi mAssistantApi;




    public XingZheApi(OkHttpClient client, ParamsAnalog paramsAnalog, AssistantApi assistantApi) {
        mParamsAnalog = paramsAnalog;

        mAssistantApi = assistantApi;


        mXingZheService = new Retrofit.Builder()
                .baseUrl("http://courier.sxgou.cn")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build()
                .create(XingZheService.class);
    }

    @Override
    public Observable<ResponseBody> addAcceptExpress(String express) {
        DispatchReq dispatchReq = new DispatchReq();
        dispatchReq.setExpressNo(express);
        dispatchReq.setIsCheck((byte) 1);
        dispatchReq.setAuxOpCode("NEW");
        FormBody.Builder builder = FormBodyBuilderFactory.create(92, dispatchReq, getExtMap(), "1001", mParamsAnalog.getXz_uuid());
        return mXingZheService.ReqData("1001", builder.build());
    }


    public Observable<JSONObject> login(String account, String pwd, String picCode, String phoneCode) {
        Date date = new Date();
        LoginReq loginReq = new LoginReq();
        loginReq.setAccount(account);
        loginReq.setPassword(PwdEncode.encode(date, pwd, account));
        loginReq.setTime(date);

        if (!TextUtils.isEmpty(picCode)) {
            loginReq.setAuthCode(picCode);
        }
        if (!TextUtils.isEmpty(phoneCode)) {
            loginReq.setPhoneAuthCode(phoneCode);
        }

        Map<String, String> extMap = PwdEncode.getLoginMap(loginReq.getAccount(), loginReq.getPassword(), loginReq.getTime(), mParamsAnalog.getDevice_imei());
        extMap.put("device", mParamsAnalog.getDevice_imei());
        extMap.put("latitude", String.valueOf(mParamsAnalog.getDevice_lat()));
        extMap.put("phoneModel", mParamsAnalog.getPhoneModel());
        extMap.put("longitude", String.valueOf(mParamsAnalog.getDevice_lng()));
        extMap.put("phoneBrand", mParamsAnalog.getPhoneBrand());
        FormBody.Builder builder = FormBodyBuilderFactory.create(2, loginReq, extMap, "0114", "");
        return mXingZheService.fetchData("0114", builder.build());
    }


    public Observable<ResponseBody> getCount() {
        FormBody.Builder builder = FormBodyBuilderFactory.create(0, null, getExtMap(), "0104", mParamsAnalog.getXz_uuid());
        return mXingZheService.ReqData("0104", builder.build());
    }


    private Map getExtMap() {
        Map<String, Object> extMap;
        extMap = new HashMap<>();
        extMap.put("latitude", mParamsAnalog.getDevice_lat());
        extMap.put("device", mParamsAnalog.getDevice_imei());
        extMap.put("phoneModel", mParamsAnalog.getPhoneModel());
        extMap.put("longitude", mParamsAnalog.getDevice_lng());
        extMap.put("phoneBrand", mParamsAnalog.getPhoneBrand());
        return extMap;
    }


    @Override
    public Observable<ResponseBody> fetchCom(String express) {
        return mAssistantApi.fetchCom(express);
    }


    public Observable<ResponseBody> getPicCode(String account) {
        Map<String, String> data = new HashMap<>();
        data.put("mobile", account);
        data.put("type", "0");
        FormBody.Builder builder = FormBodyBuilderFactory.create(3, data, getExtMap(), "0115", "");
        return mXingZheService.ReqData("0115", builder.build());
    }


    public Observable<ResponseBody> sendSms(String account) {
        Map<String, String> data = new HashMap<>();
        data.put("mobile", account);
        data.put("type", "3");
        FormBody.Builder builder = FormBodyBuilderFactory.create(3, data, getExtMap(), "0113", "");
        return mXingZheService.ReqData("0113", builder.build());
    }


    @Override
    public Observable<ResponseBody> addSignExpress(String express) {


        return fetchOrderId(express)
                .flatMap(new Func1<JSONObject, Observable<ResponseBody>>() {
                    @Override
                    public Observable<ResponseBody> call(JSONObject jsonObject) {
                        ExpressOrderRes expressOrderRes = jsonObject.getJSONObject("obj").toJavaObject(ExpressOrderRes.class);
                        return sendSignList(expressOrderRes.getId());
                    }
                });
    }


    private Observable<JSONObject> fetchOrderId(String express) {
        Map p = getExtMap();
        p.put("commonParam", express);
        FormBody.Builder builder = FormBodyBuilderFactory.create(14, null, p, "0302", mParamsAnalog.getXz_uuid());
        return mXingZheService.fetchData("0302", builder.build());
    }




    private Observable<ResponseBody> sendSignList(String orderId) {
        Map<String, Object> params = new HashMap<>();
        params.put("orderId", orderId);
        params.put("signName", "本人签收");
        params.put("signPersonType", 0);
        params.put("signTime",new Date());
        params.put("signType", 1);
        List<Object> list = new ArrayList();
        list.add(params);
        FormBody.Builder builder = FormBodyBuilderFactory.create(1, list, getExtMap(), "0307", mParamsAnalog.getXz_uuid());
        return mXingZheService.ReqData("0307", builder.build());
    }

}
